{
  stdenv,
  lib,
  fetchFromGitHub,
  fetchpatch,
  brotli,
  cmake,
  ctestCheckHook,
  giflib,
  gperftools,
  gtest,
  libhwy,
  libjpeg,
  libpng,
  libwebp,
  gdk-pixbuf,
  openexr,
  pkg-config,
  makeWrapper,
  zlib,
  asciidoc,
  graphviz,
  doxygen,
  python3,
  lcms2,
  enablePlugins ? true,
}:

let
  loadersPath = "${gdk-pixbuf.binaryDir}/jxl-loaders.cache";
in

stdenv.mkDerivation rec {
  pname = "libjxl";
  version = "0.11.1";

  outputs = [
    "out"
    "dev"
  ];

  src = fetchFromGitHub {
    owner = "libjxl";
    repo = "libjxl";
    tag = "v${version}";
    hash = "sha256-ORwhKOp5Nog366UkLbuWpjz/6sJhxUO6+SkoJGH+3fE=";
    # There are various submodules in `third_party/`.
    fetchSubmodules = true;
  };

  strictDeps = true;

  nativeBuildInputs = [
    cmake
    pkg-config
    gdk-pixbuf
    makeWrapper
    asciidoc
    doxygen
    python3
  ];

  depsBuildBuild = [
    graphviz
  ];

  # Functionality not currently provided by this package
  # that the cmake build can apparently use:
  #     OpenGL/GLUT (for Examples -> comparison with sjpeg)
  #     viewer (see `cmakeFlags`)
  #     plugins like for GDK and GIMP (see `cmakeFlags`)

  # Vendored libraries:
  # `libjxl` currently vendors many libraries as git submodules that they
  # might patch often (e.g. test/gmock, see
  # https://github.com/NixOS/nixpkgs/pull/103160#discussion_r519487734).
  # When it has stabilised in the future, we may want to tell the build
  # to use use nixpkgs system libraries.

  # As of writing, libjxl does not point out all its dependencies
  # conclusively in its README or otherwise; they can best be determined
  # by checking the CMake output for "Could NOT find".
  buildInputs = [
    lcms2
    giflib
    gperftools # provides `libtcmalloc`
    gtest
    libjpeg
    libpng
    libwebp
    gdk-pixbuf
    openexr
    zlib
  ];

  propagatedBuildInputs = [
    brotli
    libhwy
  ];

  nativeCheckInputs = [
    ctestCheckHook
  ];

  cmakeFlags = [
    # For C dependencies like brotli, which are dynamically linked,
    # we want to use the system libraries, so that we don't have to care about
    # installing their .so files generated by this build.
    # The other C++ dependencies are statically linked in, so there
    # using the vendorered ones is easier.
    "-DJPEGXL_FORCE_SYSTEM_BROTLI=ON"

    # Use our version of highway, though it is still statically linked in
    "-DJPEGXL_FORCE_SYSTEM_HWY=ON"

    # Use our version of gtest
    "-DJPEGXL_FORCE_SYSTEM_GTEST=ON"

    "-DJPEGXL_ENABLE_SKCMS=OFF"
    "-DJPEGXL_FORCE_SYSTEM_LCMS2=ON"

    # TODO: Update this package to enable this (overridably via an option):
    # Viewer tools for evaluation.
    # "-DJPEGXL_ENABLE_VIEWERS=ON"
  ]
  ++ lib.optionals enablePlugins [
    # Enable plugins, such as:
    # * the `gdk-pixbuf` one, which allows applications like `eog` to load jpeg-xl files
    # * the `gimp` one, which allows GIMP to load jpeg-xl files
    "-DJPEGXL_ENABLE_PLUGINS=ON"
  ]
  ++ lib.optionals stdenv.hostPlatform.isStatic [
    "-DJPEGXL_STATIC=ON"
  ]
  ++ lib.optionals stdenv.hostPlatform.isAarch32 [
    "-DJPEGXL_FORCE_NEON=ON"
  ];

  # the second substitution fix regex for a2x script
  # https://github.com/libjxl/libjxl/pull/3842
  postPatch = ''
    # Make sure we do not accidentally build against some of the vendored dependencies
    # If it asks you to "run deps.sh to fetch the build dependencies", then you are probably missing a JPEGXL_FORCE_SYSTEM_* flag
    shopt -s extglob
    rm -rf third_party/!(sjpeg)/
    shopt -u extglob

    # Fix the build with CMake 4.
    #
    # See:
    #
    # * <https://github.com/webmproject/sjpeg/commit/9990bdceb22612a62f1492462ef7423f48154072>
    # * <https://github.com/webmproject/sjpeg/commit/94e0df6d0f8b44228de5be0ff35efb9f946a13c9>
    substituteInPlace third_party/sjpeg/CMakeLists.txt \
      --replace-fail \
        'cmake_minimum_required(VERSION 2.8.7)' \
        'cmake_minimum_required(VERSION 3.5...3.10)'

    substituteInPlace plugins/gdk-pixbuf/jxl.thumbnailer \
      --replace '/usr/bin/gdk-pixbuf-thumbnailer' "$out/libexec/gdk-pixbuf-thumbnailer-jxl"
    substituteInPlace CMakeLists.txt \
      --replace 'sh$' 'sh( -e$|$)'
  '';

  postInstall =
    lib.optionalString enablePlugins ''
      GDK_PIXBUF_MODULEDIR="$out/${gdk-pixbuf.moduleDir}" \
      GDK_PIXBUF_MODULE_FILE="$out/${loadersPath}" \
        gdk-pixbuf-query-loaders --update-cache
    ''
    # Cross-compiled gdk-pixbuf doesn't support thumbnailers
    + lib.optionalString (enablePlugins && stdenv.hostPlatform == stdenv.buildPlatform) ''
      mkdir -p "$out/bin"
      makeWrapper ${gdk-pixbuf}/bin/gdk-pixbuf-thumbnailer "$out/libexec/gdk-pixbuf-thumbnailer-jxl" \
        --set GDK_PIXBUF_MODULE_FILE "$out/${loadersPath}"
    '';

  CXXFLAGS = lib.optionalString stdenv.hostPlatform.isAarch32 "-mfp16-format=ieee";

  # FIXME x86_64-darwin:
  # https://github.com/NixOS/nixpkgs/pull/204030#issuecomment-1352768690
  doCheck = with stdenv; !(hostPlatform.isi686 || isDarwin && isx86_64);

  disabledTests = lib.optionals stdenv.hostPlatform.isBigEndian [
    # https://github.com/libjxl/libjxl/issues/3629
    "DecodeTest.ProgressionTestLosslessAlpha"
    "DecodeTest.FlushTestLosslessProgressiveAlpha"
    "EncodeTest.FrameSettingsTest"
    "JxlTest.RoundtripAlphaResampling"
    "JxlTest.RoundtripAlphaResamplingOnlyAlpha"
    "JxlTest.RoundtripAlpha16"
    "JxlTest.RoundtripProgressive"
    "JxlTest.RoundtripProgressiveLevel2Slow"
    "ModularTest.RoundtripLossyDeltaPalette"
    "ModularTest.RoundtripLossy"
    "ModularTest.RoundtripLossy16"
    "PassesTest.ProgressiveDownsample2DegradesCorrectlyGrayscale"
    "PassesTest.ProgressiveDownsample2DegradesCorrectly"
  ];

  ctestFlags = lib.optionals stdenv.hostPlatform.isBigEndian [
    # https://github.com/libjxl/libjxl/issues/3629
    # These didn't seem to be accepted via disabledTests
    "--exclude-regex"
    ".*bitSqueeze.*"
  ];

  meta = with lib; {
    homepage = "https://github.com/libjxl/libjxl";
    description = "JPEG XL image format reference implementation";
    license = licenses.bsd3;
    maintainers = with maintainers; [ nh2 ];
    platforms = platforms.all;
  };
}
